//package cn.flying.cloud.esb.core.camel.process;
//
//import javax.annotation.Resource;
//
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.atomic.AtomicInteger;
//
//import org.apache.camel.Exchange;
//import org.apache.camel.Processor;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.cloud.client.ServiceInstance;
//import org.springframework.cloud.client.discovery.DiscoveryClient;
//import org.springframework.http.HttpMethod;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Component;
//import org.springframework.web.client.RestTemplate;
//
//import cn.flying.cloud.esb.core.camel.constants.CamelConstant;
//import cn.flying.cloud.esb.core.enums.ErrorCodeEnum;
//import cn.flying.cloud.esb.core.exception.EsbException;
//import cn.flying.cloud.esb.entity.EbAtomicService;
//import cn.flying.cloud.esb.model.ApiRequest;
//import cn.flying.cloud.esb.service.EbAtomicServiceService;
//
///**
// * 基于注册中心本地负载均衡策略（轮询）的转发地址解析处理器
// *
// * @author: admin
// * @date: 2025年04月10日 16:46
// * @version: 1.0
// */
//@Component
//public class LoadbanacerForwardProcessor implements Processor {
//    private final Logger logger = LoggerFactory.getLogger(this.getClass());
//
//    @Resource
//    private DiscoveryClient discoveryClient;
//    @Resource
//    private RestTemplate restTemplate;
//    @Resource
//    private EbAtomicServiceService atomicServiceService;
//
//    private final Map<String, AtomicInteger> serviceCounters = new ConcurrentHashMap<>();
//
//    @Override
//    public void process(Exchange exchange) throws Exception {
//        ApiRequest request = exchange.getProperty(CamelConstant.API_REQUEST, ApiRequest.class);
//
//        EbAtomicService atomicService = new EbAtomicService();
//        atomicService.setServiceCode(request.getRequest().getHead().getServiceCode());
//        atomicService = atomicServiceService.getOneObj(atomicService);
//
//        String serviceUri = atomicService.getServiceUri();
//
//        // 从请求中获取 serviceId
//        String serviceId = resolveUri(serviceUri)[0];
//
//        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
//        if (instances.isEmpty()) {
//            logger.error("No instances available for service: " + serviceId);
//            throw new EsbException(ErrorCodeEnum.E_9999);
//        }
//
//        // 获取或创建对应 serviceId 的计数器
//        AtomicInteger counter = serviceCounters.computeIfAbsent(serviceId, k -> new AtomicInteger(0));
//        int index = counter.getAndIncrement() % instances.size();
//        ServiceInstance instance = instances.get(index);
//        // 替换为实际的 API 路径
//        String url = instance.getUri() + resolveUri(serviceUri)[1];
//
//        logger.info("Selected instance: {} for serviceId: {}", instance.getUri(), serviceId);
//
//        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
//        exchange.getMessage().setBody(response.getBody());
//
//        logger.info("Successfully called service: {} with response: {}", serviceId, response.getBody());
//    }
//
//    private String[] resolveUri(String uri) {
//        String[] arr = new String[2];
//        int startIndex = uri.indexOf("//") + 2;
//        int endIndex = uri.indexOf("/", startIndex);
//        if (endIndex == -1) {
//            endIndex = uri.length();
//        }
//        arr[0] = uri.substring(startIndex, endIndex);
//        arr[1] = uri.substring(endIndex);
//        return arr;
//    }
//}
